package com.hy.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hy.common.Result;
import com.hy.entity.Users;
import com.hy.mapper.UsersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class SchoolRankingServiceImpl implements SchoolRankingService {

    @Autowired
    private UsersMapper usersMapper;

    @Override
    public Result getSchoolRanking(String keyword, Integer pageNum, Integer pageSize) {
        Page<Users> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();

        // 按积分降序，消费金额降序（模拟等级）
        wrapper.orderByDesc(Users::getPoints);

        // 关键词查询：会员号（id）精确匹配，姓名、手机号模糊匹配
        if (keyword != null && !keyword.isEmpty()) {
            wrapper.and(qw -> {
                // 检查关键词是否为数字，若是则匹配id，否则不进行id匹配
                if (keyword.matches("^[0-9]+$")) {
                    qw.eq(Users::getId, Long.parseLong(keyword));
                }
                qw.or().like(Users::getName, keyword)
                        .or().like(Users::getPhone, keyword);
            });
        }

        IPage<Users> userIPage = usersMapper.selectPage(page, wrapper);
        return Result.success(userIPage);
    }
}